﻿using FirstFloor.ModernUI.Windows.Controls;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows;
using System.Windows.Input;
using Vtron.HipcConfigurationTools.Core;
using Vtron.HipcConfigurationTools.Domain;

namespace Vtron.HipcConfigurationTools.VWASStyle
{
    /// <summary>
    /// 主窗口的 ViewModel
    /// </summary>
    public class MainWindowViewModel : INotifyPropertyChanged
    {
        #region Fields

        private static bool result;
        private string newIp;
        private SystemConfigInfo systemConfigInfo;
        private VersionInfo versionInfo;
        private NetworkInfo networkInfo;
        private string dpOrDualLink;
        private string connectionIp=String.Empty;
        private string ip;
        private string resolution;
        private SystemStatusInfo systemStatusInfo;
        private CodecType codecType;
        private string addIp = "0.0.0.0";
        private ICommand refreshCommand;
        private ICommand showSelectSignalCommand;
        private ICommand showSetDevNameCommand;
        private ICommand showSetNetConfigCommand;
        private ICommand rebootCommand;
        private ICommand exportLogCommand;
        private ICommand addCodecCommand;
        private ICommand showSetTimeCommand;
        //private ICommand searchNetworkCommand;

        #endregion

        #region Constructor

        public MainWindowViewModel()
        {
            //Socket sock2 = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            //IPEndPoint iep = new IPEndPoint(IPAddress.Any, 5010);
            //sock2.Bind(iep);
            //EndPoint ep = (EndPoint)iep;

            //SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
            //socketEventArg.RemoteEndPoint = new IPEndPoint(IPAddress.Any, 5010);
            //socketEventArg.SetBuffer(new Byte[1024], 0, 1024);
            //socketEventArg.Completed += (s, e) =>
            //{
            //    string response = string.Empty;
            //    if (e.SocketError == SocketError.Success)
            //    {
            //        response = Encoding.UTF8.GetString(e.Buffer, e.Offset, e.BytesTransferred);
            //        response = response.Trim('\0');
            //    }
            //    else
            //    {
            //        response = e.SocketError.ToString();
            //    }

            //    sock2.ReceiveFromAsync(socketEventArg);
            //};

            //sock2.ReceiveFromAsync(socketEventArg);

            Init(String.Empty, out result);
        }

        #endregion

        #region Private Helper Methods

        /// <summary>
        /// 获取编解码盒列表
        /// </summary>
        private void GetCodecList()
        {
            List<CodecInfo> codecInfoes = DataStore.GetCodecListing();
            CodecInfoes.Clear();
            EncodecInfoes.Clear();
            DecodecInfoes.Clear();
            foreach (CodecInfo codecInfo in codecInfoes.Where(c => c.CodecType == CodecType.Encoded).OrderBy(c => c.Index))
            {
                EncodecInfoes.Add(codecInfo);
                CodecInfoes.Add(codecInfo);
            }

            foreach (CodecInfo codecInfo in codecInfoes.Where(c => c.CodecType == CodecType.Decode).OrderBy(c => c.Index))
            {
                DecodecInfoes.Add(codecInfo);
                CodecInfoes.Add(codecInfo);
            }
        }

        /// <summary>
        /// 刷新
        /// </summary>
        /// <param name="obj"></param>
        private void Refresh(string obj)
        {
            Refresh();
        }

        /// <summary>
        /// 刷新
        /// </summary>
        /// <param name="obj"></param>
        private bool Refresh()
        {
            if (!SearchVersion())
            {
                return false;
            }
            if (!SearchNetConfig())
            {
                return false;
            }
            if (!SearchSystemConfig())
            {
                return false;
            }
            if (!SearchSystemStatus())
            {
                return false;
            }
            if (systemConfigInfo.BoardType == "编码板")
            {
                if (!SearchSignal())
                {
                    return false;
                }
                if (!SearchResolution())
                {
                    return false;
                }
            }
            return true;
        }

        /// <summary>
        /// 显示信号源选择窗口
        /// </summary>
        /// <param name="obj"></param>
        private void ShowSelectSignal(string obj)
        {
            SelectSignalWindow window = new SelectSignalWindow(DpOrDualLink);
            window.ShowDialog();

            SearchSignal();
        }

        /// <summary>
        /// 显示设备名设置窗口
        /// </summary>
        /// <param name="obj"></param>
        private void ShowSetDevName(string obj)
        {
            SetDevNameWindow window = new SetDevNameWindow(SystemConfigInfo.DevName);
            window.ShowDialog();

            SearchSystemConfig();
        }

        /// <summary>
        /// 显示网络参数设置窗口
        /// </summary>
        /// <param name="obj"></param>
        private void ShowSetNetConfig(string obj)
        {
            SetNetConfigWindow setNetConfigWindow = new SetNetConfigWindow(networkInfo);
            setNetConfigWindow.ShowDialog();

            if (!String.IsNullOrWhiteSpace(newIp) && newIp != ip)
            {
                CodecInfo codecInfo = EncodecInfoes.FirstOrDefault(c => c.Ip == ip);

                codecInfo = CodecInfoes.FirstOrDefault(c => c.Ip == ip);
                codecInfo.Ip = newIp;

                List<CodecInfo> codecInfoes = new List<CodecInfo>();
                codecInfoes.AddRange(EncodecInfoes);
                codecInfoes.AddRange(DecodecInfoes);
                try
                {
                    DataStore.SaveFolderListing(codecInfoes);
                }
                catch (Exception ex)
                {
                    ModernDialog.ShowMessage("本地更新Ip失败，请联系管理员！错误：" + ex.Message, "错误", MessageBoxButton.OK);
                }

                Utils.IP = newIp;
                Ip = newIp;
            }

            SearchNetConfig();
        }

        /// <summary>
        /// 显示系统时间设置窗口
        /// </summary>
        /// <param name="obj"></param>
        private void ShowSetTime(string obj)
        {
            SocketHandler handler = new SocketHandler();
            T_HIPC_TIME_GET_REQ request = new T_HIPC_TIME_GET_REQ();
            request.head = new T_HIPC_NET_HEADER() { msgType = 0x8422 };
            try
            {
                T_HIPC_TIME_GET_RESP response = handler.Handle<T_HIPC_TIME_GET_RESP>(request);
                if (response.head.msgType == 0x8423)
                {
                    if (response.head.errCode == 0)
                    {
                        SetTimeWindow window = new SetTimeWindow(response.ntpEnable == 1);
                        window.ShowDialog();

                        SearchSystemConfig();
                    }
                    else
                    {
                        ModernDialog.ShowMessage("获取系统时间失败！错误代码：" + response.head.errCode, "错误", MessageBoxButton.OK);
                    }
                }
                else
                {
                    ModernDialog.ShowMessage("获取系统时间失败！返回错误的消息代码：" + response.head.msgType, "错误", MessageBoxButton.OK);
                }
            }
            catch (Exception ex)
            {
                ModernDialog.ShowMessage("获取系统时间失败！错误信息：" + ex.Message, "错误", MessageBoxButton.OK);
            }
        }

        /// <summary>
        /// 添加编解码盒
        /// </summary>
        /// <param name="codecIp"></param>
        private void AddCodec(string codecIp)
        {
            CodecInfo codecInfo = new CodecInfo();
            codecInfo.Ip = addIp;
            codecInfo.CodecType = codecType;
            CodecInfoes.Add(codecInfo);
            try
            {
                DataStore.SaveFolderListing(CodecInfoes.ToList());
            }
            catch (Exception ex)
            {
                ModernDialog.ShowMessage(String.Format("添加{0}：{1}失败！错误信息：{2}", codecInfo.CodecType == CodecType.Encoded ? "编码盒" : "解码盒", codecInfo.Ip, ex.Message), "错误", MessageBoxButton.OK);
            }
            GetCodecList();
            ModernDialog.ShowMessage(String.Format("添加{0}：{1}成功！", codecInfo.CodecType == CodecType.Encoded ? "编码盒" : "解码盒", codecInfo.Ip), "信息", MessageBoxButton.OK);
        }

        /// <summary>
        /// 日志导出
        /// </summary>
        /// <param name="obj"></param>
        private void ExportLog(string obj)
        {
            SocketHandler handler = new SocketHandler();
            T_HIPC_SYS_EXPORT_LOG_REQ request = new T_HIPC_SYS_EXPORT_LOG_REQ();
            request.head = new T_HIPC_NET_HEADER() { msgType = 0x840c };
            string logStr = String.Empty;
            Type responseType = typeof(T_HIPC_SYS_EXPORT_LOG_RESP);
            byte[] Message = Utils.StructToBytes(request);
            TcpClient socket = new TcpClient();
            IPAddress ipAddress = IPAddress.Parse(Utils.IP);
            try
            {
                socket.Connect(ipAddress, 5001);
                NetworkStream ns = socket.GetStream();
                T_HIPC_SYS_EXPORT_LOG_RESP response = default(T_HIPC_SYS_EXPORT_LOG_RESP);
                ns.Write(Message, 0, Message.Length);
                byte[] Recv = new byte[1024];
                int NumberOfRecv = 0;
                IList<byte> newRecv = new List<byte>();
                ns.ReadTimeout = 3000;
                int size = Marshal.SizeOf(typeof(T_HIPC_NET_HEADER));
                byte[] resultRecv;
                do
                {
                    do
                    {
                        NumberOfRecv = ns.Read(Recv, 0, Recv.Length);
                        for (int i = 0; i < NumberOfRecv; i++)
                        {
                            newRecv.Add(Recv[i]);
                        }
                    }
                    while (ns.DataAvailable);
                    resultRecv = new byte[newRecv.Count];
                    newRecv.CopyTo(resultRecv, 0);

                    response = (T_HIPC_SYS_EXPORT_LOG_RESP)Utils.BytesToStruct(resultRecv, responseType);
                } while (response.head.len != newRecv.Count - size);

                logStr += Encoding.Default.GetString(resultRecv, size, resultRecv.Count() - size);

                socket.Close();
                ns.Close();
            }
            catch (Exception ex)
            {
                ModernDialog.ShowMessage("日志导出失败！" + ex.Message, "错误", MessageBoxButton.OK);
            }

            SaveFileDialog dlg = new SaveFileDialog();
            dlg.FileName = "Log";
            dlg.DefaultExt = ".text";
            dlg.Filter = "Text documents (.txt)|*.txt";
            Nullable<bool> result = dlg.ShowDialog();
            if (result == true)
            {
                string filename = dlg.FileName;
                FileStream fs = new FileStream(filename, FileMode.Create);
                StreamWriter sw = new StreamWriter(fs);
                sw.Write(logStr);
                sw.Close();
                fs.Close();
            }
        }

        /// <summary>
        /// 查询系统信息
        /// </summary>
        private bool SearchSystemConfig()
        {
            bool result = false;
            SocketHandler handler = new SocketHandler();
            HIPC_CMD_SYS_CONFIG_GET_REQ request = new HIPC_CMD_SYS_CONFIG_GET_REQ();
            request.head = new T_HIPC_NET_HEADER() { msgType = 0x8400 };
            try
            {
                HIPC_CMD_SYS_CONFIG_GET_RESP response = handler.Handle<HIPC_CMD_SYS_CONFIG_GET_RESP>(request);
                if (response.head.msgType == 0x8401)
                {
                    if (response.head.errCode == 0)
                    {
                        if (SystemConfigInfo == null)
                            SystemConfigInfo = new SystemConfigInfo();
                        if (response.sysConfig.boardType == 0)
                        {
                            SystemConfigInfo.BoardType = "编码板";
                        }
                        else
                        {
                            SystemConfigInfo.BoardType = "解码板";
                        }
                        SystemConfigInfo.DevName = new string((from c in Encoding.ASCII.GetChars(response.sysConfig.devName) where !char.IsControl(c) select c).ToArray());
                        SystemConfigInfo.SysTime = new DateTime(response.sysConfig.sysTime.year,
                                                                response.sysConfig.sysTime.month,
                                                                response.sysConfig.sysTime.day,
                                                                response.sysConfig.sysTime.hour,
                                                                response.sysConfig.sysTime.minute,
                                                                response.sysConfig.sysTime.second);

                        result = true;
                    }
                    else
                    {
                        ModernDialog.ShowMessage("查询系统信息失败！错误代码：" + response.head.errCode, "错误", MessageBoxButton.OK);
                    }
                }
                else
                {
                    ModernDialog.ShowMessage("查询系统信息失败！返回错误的消息代码：" + response.head.msgType, "错误", MessageBoxButton.OK);
                }
            }
            catch (Exception ex)
            {
                ModernDialog.ShowMessage("查询系统信息失败！错误信息：" + ex.Message, "错误", MessageBoxButton.OK);
            }
            return result;
        }

        /// <summary>
        /// 查询系统状态信息
        /// </summary>
        private bool SearchSystemStatus()
        {
            bool result = false;
            SocketHandler handler = new SocketHandler();
            T_HIPC_SYS_STATE_REQ request = new T_HIPC_SYS_STATE_REQ();
            request.head = new T_HIPC_NET_HEADER() { msgType = 0x841e };
            try
            {
                T_HIPC_SYS_STATE_RESP response = handler.Handle<T_HIPC_SYS_STATE_RESP>(request);
                if (response.head.msgType == 0x841f)
                {
                    if (response.head.errCode == 0)
                    {
                        if (SystemStatusInfo == null)
                            SystemStatusInfo = new SystemStatusInfo();
                        SystemStatusInfo.CpuLoad = response.cpuLoad;
                        SystemStatusInfo.FreeMem = response.freeMem;
                        if (response.runState == 0)
                        {
                            SystemStatusInfo.RunState = "启动";
                        }
                        else if (response.runState == 1)
                        {
                            SystemStatusInfo.RunState = "正常";
                        }
                        else if (response.runState == 2)
                        {
                            SystemStatusInfo.RunState = "错误";
                        }
                        SystemStatusInfo.RunTime = response.runTime;
                        SystemStatusInfo.Temperature = response.temperature;

                        result = true;
                    }
                    else
                    {
                        ModernDialog.ShowMessage("查询系统状态信息失败！错误代码：" + response.head.errCode, "错误", MessageBoxButton.OK);
                    }
                }
                else
                {
                    ModernDialog.ShowMessage("查询系统状态信息失败！返回错误的消息代码：" + response.head.msgType, "错误", MessageBoxButton.OK);
                }
            }
            catch (Exception ex)
            {
                ModernDialog.ShowMessage("查询系统状态信息失败！错误信息：" + ex.Message, "错误", MessageBoxButton.OK);
            }
            return result;
        }

        /// <summary>
        /// 查询版本信息
        /// </summary>
        private bool SearchVersion()
        {
            bool result = false;
            SocketHandler handler = new SocketHandler();
            T_HIPC_SYS_VERSION_REQ request = new T_HIPC_SYS_VERSION_REQ();
            request.head = new T_HIPC_NET_HEADER() { msgType = 0x8402 };
            try
            {
                T_HIPC_SYS_VERSION_RESP response = handler.Handle<T_HIPC_SYS_VERSION_RESP>(request);
                if (response.head.msgType == 0x8403)
                {
                    if (response.head.errCode == 0)
                    {
                        if (VersionInfo == null)
                            VersionInfo = new VersionInfo();
                        VersionInfo.Software = String.Format("{0}.{1}.{2}", response.softVersion[2], response.softVersion[1], response.softVersion[0]);
                        VersionInfo.FPGA = String.Format("{0}.{1}.{2}", response.fpgaVersion[2], response.fpgaVersion[1], response.fpgaVersion[0]);
                        VersionInfo.Hardware = ((char)response.hardVersion).ToString();
                        VersionInfo.PCBA = String.Format("{0}", response.pcbaVersion);

                        result = true;
                    }
                    else
                    {
                        ModernDialog.ShowMessage("查询版本信息失败！错误代码：" + response.head.errCode, "错误", MessageBoxButton.OK);
                    }
                }
                else
                {
                    ModernDialog.ShowMessage("查询版本信息失败！返回错误的消息代码：" + response.head.msgType, "错误", MessageBoxButton.OK);
                }
            }
            catch (Exception ex)
            {
                ModernDialog.ShowMessage("查询版本信息失败！错误信息：" + ex.Message, "错误", MessageBoxButton.OK);
            }
            return result;
        }

        /// <summary>
        /// 获取信号源
        /// </summary>
        private bool SearchSignal()
        {
            bool result = false;
            SocketHandler handler = new SocketHandler();
            T_HIPC_SIGNAL_SELECT_REQ request = new T_HIPC_SIGNAL_SELECT_REQ();
            request.head = new T_HIPC_NET_HEADER() { msgType = 0x8502 };
            try
            {
                T_HIPC_SIGNAL_SELECT_RESP response = handler.Handle<T_HIPC_SIGNAL_SELECT_RESP>(request);
                if (response.head.msgType == 0x8503)
                {
                    if (response.head.errCode == 0)
                    {
                        DpOrDualLink = response.dpOrDualLink == 0 ? "dp信号" : "duallink信号";

                        result = true;
                    }
                    else
                    {
                        ModernDialog.ShowMessage("获取信号源失败！错误代码：" + response.head.errCode, "错误", MessageBoxButton.OK);
                    }
                }
                else
                {
                    ModernDialog.ShowMessage("获取信号源失败！返回错误的消息代码：" + response.head.msgType, "错误", MessageBoxButton.OK);
                }
            }
            catch (Exception ex)
            {
                ModernDialog.ShowMessage("获取信号源失败！错误信息：" + ex.Message, "错误", MessageBoxButton.OK);
            }
            return result;
        }

        /// <summary>
        /// 获取信号源分辨率
        /// </summary>
        private bool SearchResolution()
        {
            bool result = false;
            SocketHandler handler = new SocketHandler();
            T_HIPC_SIGNAL_RESOLUTION_REQ request = new T_HIPC_SIGNAL_RESOLUTION_REQ();
            request.head = new T_HIPC_NET_HEADER() { msgType = 0x8504 };
            try
            {
                T_HIPC_SIGNAL_RESOLUTION_RESP response = handler.Handle<T_HIPC_SIGNAL_RESOLUTION_RESP>(request);
                if (response.head.msgType == 0x8505)
                {
                    if (response.head.errCode == 0)
                    {
                        Resolution = String.Format("{0} * {1}", response.width, response.height);

                        result = true;
                    }
                    else
                    {
                        ModernDialog.ShowMessage("获取信号源分辨率失败！错误代码：" + response.head.errCode, "错误", MessageBoxButton.OK);
                    }
                }
                else
                {
                    ModernDialog.ShowMessage("获取信号源分辨率失败！返回错误的消息代码：" + response.head.msgType, "错误", MessageBoxButton.OK);
                }
            }
            catch (Exception ex)
            {
                ModernDialog.ShowMessage("获取信号源分辨率失败！错误信息：" + ex.Message, "错误", MessageBoxButton.OK);
            }
            return result;
        }

        /// <summary>
        /// 重启
        /// </summary>
        /// <param name="obj"></param>
        private void Reboot(string obj)
        {
            SocketHandler handler = new SocketHandler();
            T_HIPC_SYS_REBOOT_REQ request = new T_HIPC_SYS_REBOOT_REQ();
            request.head = new T_HIPC_NET_HEADER() { msgType = 0x8406 };
            try
            {
                T_HIPC_SYS_REBOOT_RESP response = handler.Handle<T_HIPC_SYS_REBOOT_RESP>(request);
                if (response.head.msgType == 0x8407)
                {
                    if (response.head.errCode == 0)
                    {
                    }
                    else
                    {
                        ModernDialog.ShowMessage("重启失败！错误代码：" + response.head.errCode, "错误", MessageBoxButton.OK);
                    }
                }
                else
                {
                    ModernDialog.ShowMessage("重启失败！返回错误的消息代码：" + response.head.msgType, "错误", MessageBoxButton.OK);
                }
            }
            catch (Exception ex)
            {
                ModernDialog.ShowMessage("重启失败！错误信息：" + ex.Message, "错误", MessageBoxButton.OK);
            }
        }

        ///// <summary>
        ///// 广播查询网络
        ///// </summary>
        ///// <param name="obj"></param>
        //private void SearchNetwork(string obj)
        //{
        //    Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        //    IPEndPoint iep1 = new IPEndPoint(IPAddress.Broadcast, 5010);
        //    string hostname = Dns.GetHostName();
        //    byte[] data = Encoding.ASCII.GetBytes(hostname);
        //    sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
        //    sock.SendTo(data, iep1);
        //    sock.Close();
        //}

        #endregion

        #region Public Methods

        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="result"></param>
        public void Init(string ip, out bool result)
        {
            result = false;

            //searchNetworkCommand = new DelegateCommand<string>(SearchNetwork);
            showSetNetConfigCommand = new DelegateCommand<string>(ShowSetNetConfig);
            exportLogCommand = new DelegateCommand<string>(ExportLog);
            addCodecCommand = new DelegateCommand<string>(AddCodec);
            showSetTimeCommand = new DelegateCommand<string>(ShowSetTime);
            rebootCommand = new DelegateCommand<string>(Reboot);
            showSetDevNameCommand = new DelegateCommand<string>(ShowSetDevName);
            showSelectSignalCommand = new DelegateCommand<string>(ShowSelectSignal);
            refreshCommand = new DelegateCommand<string>(Refresh);
            CodecInfoes = new ObservableCollection<CodecInfo>();
            EncodecInfoes = new ObservableCollection<CodecInfo>();
            DecodecInfoes = new ObservableCollection<CodecInfo>();
            GetCodecList();

            if (string.IsNullOrEmpty(ip))
            {
                return;
            }

            Utils.IP = ip;
            Ip = ip;
            foreach (var encodedDecodedConnectionIp in Utils.EncodedDecodedConnectionDictionary)
            {
                if (encodedDecodedConnectionIp.Key == ip)
                {
                    ConnectionIp += encodedDecodedConnectionIp.Value + "\r\n";
                }
                else if (encodedDecodedConnectionIp.Value == ip)
                {
                    ConnectionIp += encodedDecodedConnectionIp.Key + "\r\n";
                }
            }

            result = Refresh();
        }

        /// <summary>
        /// 保存编解码盒列表
        /// </summary>
        public void SaveCodecList()
        {
            try
            {
                DataStore.SaveFolderListing(CodecInfoes.ToList());
            }
            catch (Exception ex)
            {
                ModernDialog.ShowMessage("保存编解码盒列表失败！" + ex.Message, "错误", MessageBoxButton.OK);
            }

            GetCodecList();
        }

        /// <summary>
        /// 测试网络连接
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        public bool TestConnect(string ip)
        {
            TcpClient socket = new TcpClient();
            IPAddress ipAddress = IPAddress.Parse(ip);
            try
            {
                socket.Connect(ipAddress, 5001);
                socket.Close();
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 查询网络配置信息
        /// </summary>
        public bool SearchNetConfig()
        {
            bool result = false;
            SocketHandler handler = new SocketHandler();
            T_HIPC_NET_CONFIG_REQ request = new T_HIPC_NET_CONFIG_REQ();
            request.head = new T_HIPC_NET_HEADER() { msgType = 0x8408 };
            request.netInfo = new T_HIPC_NET_INFO();
            try
            {
                T_HIPC_NET_CONFIG_RESP response = handler.Handle<T_HIPC_NET_CONFIG_RESP>(request);
                if (response.head.msgType == 0x8409)
                {
                    if (response.head.errCode == 0)
                    {
                        if (NetworkInfo == null)
                            NetworkInfo = new NetworkInfo();
                        NetworkInfo.IsDHCP = response.dhcp == 1;
                        NetworkInfo.Ip = new string((from c in Encoding.ASCII.GetChars(response.netInfo.ipAddress) where !char.IsControl(c) select c).ToArray());
                        NetworkInfo.Mask = new string((from c in Encoding.ASCII.GetChars(response.netInfo.netMask) where !char.IsControl(c) select c).ToArray());
                        NetworkInfo.Gateway = new string((from c in Encoding.ASCII.GetChars(response.netInfo.gatway) where !char.IsControl(c) select c).ToArray());
                        NetworkInfo.Mac = new string((from c in Encoding.ASCII.GetChars(response.netInfo.macAddress) where !char.IsControl(c) select c).ToArray());

                        result = true;
                    }
                    else
                    {
                        ModernDialog.ShowMessage("查询网络配置信息失败！错误代码：" + response.head.errCode, "错误", MessageBoxButton.OK);
                    }
                }
                else
                {
                    ModernDialog.ShowMessage("查询网络配置信息失败！返回错误的消息代码：" + response.head.msgType, "错误", MessageBoxButton.OK);
                }
            }
            catch (Exception ex)
            {
                ModernDialog.ShowMessage("查询网络配置信息失败！错误信息：" + ex.Message, "错误", MessageBoxButton.OK);
            }
            return result;
        }

        /// <summary>
        /// 删除编解码卡
        /// </summary>
        /// <param name="codecIp"></param>
        public void DeleteCodec(string codecIp)
        {
            CodecInfo codecInfo = EncodecInfoes.FirstOrDefault(c => c.Ip == codecIp);
            if (codecInfo == null)
            {
                codecInfo = DecodecInfoes.FirstOrDefault(c => c.Ip == codecIp);
                DecodecInfoes.Remove(codecInfo);
            }
            else
            {
                EncodecInfoes.Remove(codecInfo);
            }
            CodecInfoes.Remove(codecInfo);

            List<CodecInfo> codecInfoes = new List<CodecInfo>();
            codecInfoes.AddRange(EncodecInfoes);
            codecInfoes.AddRange(DecodecInfoes);
            try
            {
                DataStore.SaveFolderListing(codecInfoes);
            }
            catch (Exception ex)
            {
                ModernDialog.ShowMessage("删除失败！" + ex.Message, "错误", MessageBoxButton.OK);
            }
        }

        /// <summary>
        /// 编解码视频连接
        /// </summary>
        /// <param name="encodecIp"></param>
        /// <param name="decodecIp"></param>
        public bool EncodedDecodedConnection(string encodecIp, string decodecIp)
        {
            SocketHandler handler = new SocketHandler();
            T_HIPC_VWAS_DEC_VIDEO_CONNECT_REQ request = new T_HIPC_VWAS_DEC_VIDEO_CONNECT_REQ();
            request.head = new T_HIPC_NET_HEADER() { msgType = 0x8001 };
            request.srcIP = Encoding.Default.GetBytes(encodecIp).Concat(new byte[20 - Encoding.Default.GetBytes(encodecIp).Count()]).ToArray();
            try
            {
                T_HIPC_VWAS_DEC_VIDEO_CONNECT_RESP response = (T_HIPC_VWAS_DEC_VIDEO_CONNECT_RESP)handler.Handle<T_HIPC_VWAS_DEC_VIDEO_CONNECT_RESP>(request, decodecIp, Utils.PORT);

                if (response.head.msgType == 0x8002)
                {
                    if (response.head.errCode == 0)
                    {
                        ModernDialog.ShowMessage(String.Format("编码盒：{0}与解码盒：{1}连接成功！", encodecIp, decodecIp), "信息", MessageBoxButton.OK);

                        if (Utils.EncodedDecodedConnectionDictionary.ContainsKey(decodecIp))
                        {
                            Utils.EncodedDecodedConnectionDictionary[decodecIp] = encodecIp;
                        }
                        else
                        {
                            Utils.EncodedDecodedConnectionDictionary.Add(decodecIp, encodecIp);
                        }

                        if (decodecIp == Utils.IP)
                        {
                            ConnectionIp += encodecIp + "\r\n";
                        }
                        else if (encodecIp == Utils.IP)
                        {
                            ConnectionIp += decodecIp + "\r\n";
                        }
                        return true;
                    }
                    else
                    {
                        ModernDialog.ShowMessage("编解码视频连接失败！错误代码：" + response.head.errCode, "错误", MessageBoxButton.OK);
                    }
                }
                else
                {
                    ModernDialog.ShowMessage("编解码视频连接失败！返回错误的消息代码：" + response.head.msgType, "错误", MessageBoxButton.OK);
                }
            }
            catch (Exception ex)
            {
                ModernDialog.ShowMessage("编解码视频连接失败！错误信息：" + ex.Message, "错误", MessageBoxButton.OK);
            }
            return false;
        }

        /// <summary>
        /// 编解码视频连接断开
        /// </summary>
        /// <param name="encodecIp"></param>
        /// <param name="decodecIp"></param>
        public bool EncodedDecodedDisconnection(string decodecIp)
        {
            bool result = false;
            SocketHandler handler = new SocketHandler();
            T_HIPC_VWAS_DEC_VIDEO_DISCONNECT_REQ request = new T_HIPC_VWAS_DEC_VIDEO_DISCONNECT_REQ();
            request.head = new T_HIPC_NET_HEADER() { msgType = 0x8003 };
            try
            {
                T_HIPC_VWAS_DEC_VIDEO_DISCONNECT_RESP response = (T_HIPC_VWAS_DEC_VIDEO_DISCONNECT_RESP)handler.Handle<T_HIPC_VWAS_DEC_VIDEO_DISCONNECT_RESP>(request, decodecIp, Utils.PORT);
                if (response.head.msgType == 0x8004)
                {
                    if (response.head.errCode == 0)
                    {
                        ModernDialog.ShowMessage(String.Format("解码盒：{0}断开连接成功！", decodecIp), "信息", MessageBoxButton.OK);

                        if (Utils.EncodedDecodedConnectionDictionary.ContainsKey(decodecIp))
                        {
                            Utils.EncodedDecodedConnectionDictionary.Remove(decodecIp);
                        }

                        if (decodecIp == Utils.IP)
                        {
                            ConnectionIp = String.Empty;
                        }
                        else if (ConnectionIp.Contains(decodecIp))
                        {
                            ConnectionIp.Replace(decodecIp + "\r\n", String.Empty);
                        }
                        result = true;
                    }
                    else
                    {
                        ModernDialog.ShowMessage("编解码视频连接断开失败！错误代码：" + response.head.errCode, "错误", MessageBoxButton.OK);
                    }
                }
                else
                {
                    ModernDialog.ShowMessage("编解码视频连接断开失败！返回错误的消息代码：" + response.head.msgType, "错误", MessageBoxButton.OK);
                }
            }
            catch (Exception ex)
            {
                ModernDialog.ShowMessage("编解码视频连接断开失败！错误信息：" + ex.Message, "错误", MessageBoxButton.OK);
            }

            return result;
        }

        #endregion

        #region Commands

        public ICommand RefreshCommand { get { return refreshCommand; } }

        public ICommand ShowSelectSignalCommand { get { return showSelectSignalCommand; } }

        public ICommand ShowSetDevNameCommand { get { return showSetDevNameCommand; } }

        public ICommand ShowSetNetConfigCommand { get { return showSetNetConfigCommand; } }

        public ICommand RebootCommand { get { return rebootCommand; } }

        public ICommand ExportLogCommand { get { return exportLogCommand; } }

        public ICommand AddCodecCommand { get { return addCodecCommand; } }

        public ICommand ShowSetTimeCommand { get { return showSetTimeCommand; } }

        //public ICommand SearchNetworkCommand { get { return searchNetworkCommand; } } 

        #endregion

        #region ObservableCollections

        public ObservableCollection<CodecInfo> CodecInfoes { get; private set; }

        public ObservableCollection<CodecInfo> EncodecInfoes { get; private set; }

        public ObservableCollection<CodecInfo> DecodecInfoes { get; private set; }

        public ObservableCollection<CodecInfo> NetworkCodecInfoes { get; private set; }

        #endregion

        #region Properties

        ///// <summary>
        ///// 修改后的网络Ip
        ///// </summary>
        //public string NewIp
        //{
        //    get
        //    {
        //        return newIp;
        //    }
        //    set
        //    {
        //        newIp = value;
        //    }
        //}

        /// <summary>
        /// 系统信息
        /// </summary>
        public SystemConfigInfo SystemConfigInfo
        {
            get { return systemConfigInfo; }
            set
            {
                systemConfigInfo = value;

                if (PropertyChanged != null)
                {
                    PropertyChanged.Invoke(this, new PropertyChangedEventArgs("SystemConfigInfo"));
                }
            }
        }

        /// <summary>
        /// 版本信息
        /// </summary>
        public VersionInfo VersionInfo
        {
            get { return versionInfo; }
            set
            {
                versionInfo = value;

                if (PropertyChanged != null)
                {
                    PropertyChanged.Invoke(this, new PropertyChangedEventArgs("VersionInfo"));
                }
            }
        }

        /// <summary>
        /// 网络参数
        /// </summary>
        public NetworkInfo NetworkInfo
        {
            get { return networkInfo; }
            set
            {
                networkInfo = value;

                if (PropertyChanged != null)
                {
                    PropertyChanged.Invoke(this, new PropertyChangedEventArgs("NetworkInfo"));
                }
            }
        }

        /// <summary>
        /// 系统状态信息
        /// </summary>
        public SystemStatusInfo SystemStatusInfo
        {
            get { return systemStatusInfo; }
            set
            {
                systemStatusInfo = value;

                if (PropertyChanged != null)
                {
                    PropertyChanged.Invoke(this, new PropertyChangedEventArgs("SystemStatus"));
                }
            }
        }

        /// <summary>
        /// 信号源
        /// </summary>
        public string DpOrDualLink
        {
            get { return dpOrDualLink; }
            set
            {
                dpOrDualLink = value;

                if (PropertyChanged != null)
                {
                    PropertyChanged.Invoke(this, new PropertyChangedEventArgs("DpOrDualLink"));
                }
            }
        }

        /// <summary>
        /// 视频连接的板卡Ip
        /// </summary>
        public string ConnectionIp
        {
            get { return connectionIp; }
            set
            {
                connectionIp = value;

                if (PropertyChanged != null)
                {
                    PropertyChanged.Invoke(this, new PropertyChangedEventArgs("ConnectionIp"));
                }
            }
        }

        /// <summary>
        /// 板卡Ip
        /// </summary>
        public string Ip
        {
            get { return ip; }
            set
            {
                ip = value;

                if (PropertyChanged != null)
                {
                    PropertyChanged.Invoke(this, new PropertyChangedEventArgs("Ip"));
                }
            }
        }

        /// <summary>
        /// 分辨率
        /// </summary>
        public string Resolution
        {
            get { return resolution; }
            set
            {
                resolution = value;

                if (PropertyChanged != null)
                {
                    PropertyChanged.Invoke(this, new PropertyChangedEventArgs("Resolution"));
                }
            }
        }

        /// <summary>
        /// 板卡类型
        /// </summary>
        public CodecType CodecType
        {
            get { return codecType; }
            set
            {
                codecType = value;

                if (PropertyChanged != null)
                {
                    PropertyChanged.Invoke(this, new PropertyChangedEventArgs("CodecType"));
                }
            }
        }

        /// <summary>
        /// 新增的板卡Ip
        /// </summary>
        public string AddIp
        {
            get { return addIp; }
            set
            {
                addIp = value;

                if (PropertyChanged != null)
                {
                    PropertyChanged.Invoke(this, new PropertyChangedEventArgs("AddIp"));
                }
            }
        }

        #endregion

        public event PropertyChangedEventHandler PropertyChanged;

        public ICommand deleteCodecCommand { get; set; }
    }
}
